from datetime import datetime
import json
import time
from django.shortcuts import render

from django.views import View
from django.http import JsonResponse
from rbac.models import AdminUsers, Department, Roles
import jwt

from rbac.utils import *

# Create your views here.


class Login(View):

    def get(self, request):

        list1 = Department.objects.filter().values()

        listdata = getTree(list(list1), 0)

        return JsonResponse({
            'code': 200,
            'data': listdata,
        })

    def post(self, request):
        try:
            body = json.loads(request.body)
            username = body.get("username")
            password = body.get("password")

            # 判断用户名是否为空
            if (len(username) <= 0 or len(password) <= 0):
                return JsonResponse({
                    'status': "error",
                    'msg': "用户名和密码不能为空"
                })

            # 查询用户是否存在，如果不存在提示错误信息
            user = AdminUsers.objects.filter(
                username=username, mg_status=1).first()

            if (not user):

                return JsonResponse({
                    'status': "error",
                    'msg': "用户名不存在"
                })

            else:
                # 密码是否一致
                if (user.password != password):
                    return JsonResponse({
                        'status': 'error',
                        'msg': "密码错误"
                    })
                else:

                    # 登录成功生成token值，更新token值
                    dict = {"name": user.username, "password": user.password}
                    token = jwt.encode(dict, "login_token", algorithm="HS256")

                    print(token)
                    # 更新token到用户表中去，生成token的信息内容
                    AdminUsers.objects.filter(id=user.id).update(
                        token=token, expired_at=time.time()+7200)

                    roles = user.roles.filter().first()  # 查询角色的信息

                    return JsonResponse({
                        'status': 'ok',
                        'type': 'account',
                        'currentAuthority': 'admin',
                        # 返回用户的基本信息
                        'data': {
                            'id': user.id,
                            'username': user.username,
                            'token': token,
                            'role_name': roles.role_name,
                        }
                    })

        except Exception:
            return JsonResponse({
                'status': "error",
                'msg': "登录失败"
            })

### 退出登录效果
class Logout(View):
    def post(self, request):
        try:
            # 获取token值
            token = request.META.get("HTTP_AUTHORIZATION")

            AdminUsers.objects.filter(token=token).update(expired_at=time.time()-1)

            return JsonResponse({
                'code':200,
                'msg':"退出成功"
            })
        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'msg': '退出失败'
            })

# 获取当前用户信息内容


class CurrentUser(View):

    def get(self, request):
        # 获取token值,通过token获取用户详情的基本信息内容
        token = request.META.get("HTTP_AUTHORIZATION")
        user = AdminUsers.objects.filter(token=token).first()

        roles = user.roles.filter().first()

        roles_list = Roles.objects.filter().values('role_code')

        return JsonResponse({
            'success': True,
            'data': {
                "name": user.username,
                "avatar": user.profile_picture,
                'id': user.id,
                "access": roles.role_code,
                'code':roles.role_code,
                'roles_list':list(roles_list)
            }
        })

# 用户增删改查相关数据


class Users(View):

    def get(self, request):
        query = request.GET
        username = query.get("username")
        email = query.get("email")
        mg_status = query.get("mg_status")
        depart_id = query.get("depart_id")

        user = AdminUsers.objects

        print(username)
        # 获取用户列表数据的内容
        if (username):
            user = user.filter(username__contains=username)

        if (email):
            user = user.filter(email__contains=email)

        if (mg_status):
            user = user.filter(mg_status=mg_status)
        if (depart_id):
            user = user.filter(depart__id=depart_id)

        user = user.values('id', 'depart__name', 'roles__role_code', 'roles__role_name',
                           'username', 'email', 'mg_status', 'profile_picture', 'depart__id', 'roles__id')

        return JsonResponse({
            'code': 200,
            'data': list(user),
            'msg': "获取列表数据成功",
            'total': len(list(user))
        })

    def post(self, request):
        print("234234234")
        try:
            # 获取数据内容
            body = json.loads(request.body)
            print(body)
            username = body.get("username")
            password = body.get("password")
            email = body.get("email")
            mg_status = body.get("mg_status")
            depart_id = body.get("depart_id")
            role_id = body.get("role_id")

            if (not username or not password or not email or mg_status is None):
                return JsonResponse({
                    'code': 400,
                    'msg': "参数错误"
                })

            print(username, password, '123123')

            res = AdminUsers.objects.create(
                username=username, password=password, email=email, mg_status=mg_status)
            print(res.id)

            user = AdminUsers.objects.filter(id=res.id).first()

            user.depart.add(depart_id)  # 添加关联记录

            user.roles.add(role_id)  # 添加角色关联记录

            return JsonResponse({
                'code': 200,
                'msg': "创建用户数据成功"
            })
        except Exception as err:
            return JsonResponse({
                'status': "error",
                'msg': format(err)
            })

    # 更新用户数据
    def put(self, request):
        try:
            # 获取数据内容
            body = json.loads(request.body)
            id = body.get("id")
            username = body.get("username")
            password = body.get("password")
            email = body.get("email")
            mg_status = body.get("mg_status")
            depart_id = body.get("depart_id")
            role_id = body.get("role_id")  # //角色id

            users = AdminUsers.objects.filter(id=id).first()

            if (username):
                users.username = username
            if (password):
                users.password = password

            if (email):
                users.email = email

            if (mg_status != None):
                users.mg_status = mg_status

            users.save()

            if (depart_id):
                users.depart.set([depart_id])  # 修改部门信息
            if (role_id):
                users.roles.set([role_id])  # 修改角色的信息

            return JsonResponse({
                'code': 200,
                'msg': "修改用户数据成功"
            })

        except Exception as err:
            return JsonResponse({
                'status': "error",
                'msg': format(err)
            })

    # 删除用户的数据
    def delete(self, request):
        try:

            body = json.loads(request.body)

            id = body.get("id")

            AdminUsers.objects.get(id=id).delete()

            return JsonResponse({
                'code': 200,
                'msg': "删除用户数据成功"
            })

        except Exception as e:

            return JsonResponse({
                'status': "error",
                'msg': format(e)
            })
# 用户列表数据成功
# class UserList(View):
